from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .models import Area
from .serializers import AreaSerializer, AreaDetailSerializer
from rest_framework import status
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin


# class AreaListView(APIView):
#     """查询所有省"""
#
#     def get(self, request):
#         # 1、获取指定的查询集
#         qs = Area.objects.filter(parent=None)
#         # 2、创建序列化器进行序列化
#         serializer = AreaSerializer(instance=qs, many=True)
#         # 3、返回数据
#         return Response(serializer.data)
#
#
# class AreaDetailView(APIView):
#     """查询单一省或市"""
#
#     def get(self, request, pk):
#         # 1、根据pk查询出指定的省或市
#         try:
#             qs = Area.objects.get(pk=pk)
#         except Area.DoesNotExist:
#             return Response({"message": "无效id"}, status=status.HTTP_400_BAD_REQUEST)
#         # 2、创建序列化器
#         serializer = AreaDetailSerializer(instance=qs)
#         # 3、返回数据
#         return Response(serializer.data)


# class AreaListView(ListAPIView):
#     """查询所有省"""
#     serializer_class = AreaSerializer
#     queryset = Area.objects.filter(parent=None)
#
#
# class AreaDetailView(RetrieveAPIView):
#     """查询单一省或市"""
#     serializer_class = AreaDetailSerializer
#     queryset = Area.objects


class AreaViewSet(
    CacheResponseMixin, ReadOnlyModelViewSet
):  # CacheResponseMixin 缓存类，必须要写在前面
    """简化"""

    # serializer_class = AreaSerializer

    # queryset =
    def get_queryset(self):
        if self.action == "list":
            return Area.objects.filter(parent=None)
        else:
            return Area.objects

    def get_serializer_class(self):
        if self.action == "list":
            return AreaSerializer
        else:
            return AreaDetailSerializer
